package top.drinyeit.nongmao.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import top.drinyeit.nongmao.R;
import top.drinyeit.nongmao.activity.GoodsShopClassificationActivity;
import top.drinyeit.nongmao.activity.MainActivity;
import top.drinyeit.nongmao.activity.ShopInnerGoodsActivity;
import top.drinyeit.nongmao.adapter.HomeIconAdapter;
import top.drinyeit.nongmao.adapter.ShopBottomGoodsAdapter;
import top.drinyeit.nongmao.adapter.ShopCenterClassfyAdapter;
import top.drinyeit.nongmao.base.LazyFragment;
import top.drinyeit.nongmao.interfaces.IResult;
import top.drinyeit.nongmao.interfaces.OnItemClickListener;
import top.drinyeit.nongmao.model.AppHomeBean;
import top.drinyeit.nongmao.model.CategoryGoodsDetailsBean;
import top.drinyeit.nongmao.presenter.ShopPresenter;
import top.drinyeit.nongmao.retrofit.HttpResponse;
import top.drinyeit.nongmao.view.ObservableScrollView;
import top.drinyeit.nongmao.view.dropdown.DropDownMenu;


/**
 * Created by Administrator on 2018/3/15.
 */

public class ShopFragment extends LazyFragment implements View.OnClickListener, ObservableScrollView.ScrollViewListener {

    public ImageView banner;
    public RecyclerView categoryRecyclerView, shop_center_classfy, rv_shop_list;
    private ShopPresenter shopPresenter;
    private HomeIconAdapter homeIconAdapter;
    private LinearLayout ll_classfy_top, ll_classfy_bottom;
    private ObservableScrollView obserVerScrollView;
    private String headers[] = {"商家分类", "智能排序", "优惠活动"};
    private String citys[] = {"商家分类", "分类1", "分类2", "分类3"};
    private String ages[] = {"智能排序", "由高到低", "由低到高"};
    private String constellations[] = {"优惠活动", "活动一", "活动二", "活动三", "活动四"};
    DropDownMenu mDropDownMenu, mDropDownMenu2;
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_SHOP, DropDownMenu.TYPE_LIST_SORT, DropDownMenu.TYPE_ACTIVITY};
    private ShopCenterClassfyAdapter centerAdapter;
    private ShopBottomGoodsAdapter shopBottomAdapter;
    ImageView iv_back;
    TextView tv_title;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_shop;
    }

    @Override
    protected void initViews() {
        banner = mRootView.findViewById(R.id.iv_banner);
        categoryRecyclerView = mRootView.findViewById(R.id.rv_shop_category);
        shop_center_classfy = mRootView.findViewById(R.id.shop_center_classfy);
        rv_shop_list = mRootView.findViewById(R.id.rv_shop_list);
        obserVerScrollView = mRootView.findViewById(R.id.obserVerScrollView);
        obserVerScrollView.setScrollViewListener(this);
        ll_classfy_top = mRootView.findViewById(R.id.ll_classfy_top);
        ll_classfy_bottom = mRootView.findViewById(R.id.ll_classfy_bottom);
        mDropDownMenu = mRootView.findViewById(R.id.mDropDownMenu);
        mDropDownMenu2 = mRootView.findViewById(R.id.mDropDownMenu2);
        setTitle(false,"商铺");
//        iv_back = mRootView.findViewById(R.id.iv_back);
//        tv_title = mRootView.findViewById(R.id.tv_title);
//        iv_back.setVisibility(View.GONE);
//        tv_title.setText("商铺");
//
//        View state = mRootView.findViewById(R.id.v_state);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            state.setBackgroundColor(ContextCompat.getColor(this.getActivity(), R.color.transparent_03));
//        } else {
//            state.setBackgroundColor(ContextCompat.getColor(this.getActivity(), R.color.transparent));
//        }

        initHeader();
    }

    private void initHeader() {
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), rv_shop_list);
        mDropDownMenu2.setDropDownMenu(Arrays.asList(headers), initViewData(), rv_shop_list);
        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener(new DropDownMenu.OnDefultMenuSelectListener() {
            @Override
            public void onSelectDefaultMenu(int index, int pos, String clickstr) {
                //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
                Toast.makeText(getActivity(), clickstr, Toast.LENGTH_SHORT).show();
            }
        });
        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu2.addMenuSelectListener(new DropDownMenu.OnDefultMenuSelectListener() {
            @Override
            public void onSelectDefaultMenu(int index, int pos, String clickstr) {
                //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
                Toast.makeText(getActivity(), clickstr, Toast.LENGTH_SHORT).show();
            }
        });
        mDropDownMenu.setOnMyClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(view);
            }
        });
        mDropDownMenu2.setOnMyClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(view);
            }
        });
    }

    final String[] datas = {"选项1", "选项2", "选项3", "选项4", "选项5"};

    private void showPopupWindow(View view) {
        // TODO: 2016/5/17 构建一个popupwindow的布局
        View popupView = getLayoutInflater().inflate(R.layout.popupwindow, null);

        // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。
        ListView lsvMore = popupView.findViewById(R.id.lsvMore);
        lsvMore.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, datas));

        // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
        PopupWindow window = new PopupWindow(popupView, mDropDownMenu.getTabWidth(), 600);
        // TODO: 2016/5/17 设置动画
//                window.setAnimationStyle(R.style.popup_window_anim);
        // TODO: 2016/5/17 设置背景颜色
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        // TODO: 2016/5/17 设置可以获取焦点
        window.setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
        // TODO：更新popupwindow的状态
        window.update();
        // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
        window.showAsDropDown(view, 0, 0);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mDropDownMenu.closeMenu();
                mDropDownMenu2.closeMenu();
            }
        });
        lsvMore.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
    }

    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            switch (types[i]) {
                case DropDownMenu.TYPE_LIST_SHOP:
                    map.put(DropDownMenu.VALUE, citys);
                    map.put(DropDownMenu.SELECT_POSITION, 0);
                    break;
                case DropDownMenu.TYPE_LIST_SORT:
                    map.put(DropDownMenu.VALUE, ages);
                    map.put(DropDownMenu.SELECT_POSITION, 0);
                    break;
                case DropDownMenu.TYPE_ACTIVITY:
                    map.put(DropDownMenu.VALUE, constellations);
                    map.put(DropDownMenu.SELECT_POSITION, 0);
                    break;
            }
            viewDatas.add(map);
        }
        return viewDatas;
    }


    @Override
    protected void lazyLoad() {
        shopPresenter = new ShopPresenter(this, new IResult() {
            @Override
            public void success(@NotNull String arg1, @NotNull Object arg2) {
                showToastMsg(arg1);
                HttpResponse<AppHomeBean> response = (HttpResponse<AppHomeBean>) arg2;
                int c = response.getData().getCommodity().size();
                final int b = response.getData().getBanner().size();
                int ca = response.getData().getCategory().size();

                //设置分类
                if (homeIconAdapter == null) {
                    homeIconAdapter = new HomeIconAdapter(response.getData().getCategory());
                    categoryRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
                    homeIconAdapter.setOnItemClickListener(new HomeIconAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent = new Intent(getActivity(), GoodsShopClassificationActivity.class);
//                            intent.putExtra("category", response.getData().getCategory().get(position));
//                            intent.putExtra("type", "home");
                            startActivity(intent);
                        }
                    });
                    categoryRecyclerView.setAdapter(homeIconAdapter);
                    categoryRecyclerView.setNestedScrollingEnabled(false);
                }

//                if (cvAdapter == null) {
//                    banner = o.getData().getBanner();
//                    cvAdapter = new CVAdapter(fragment.getActivity(), banner);
//                    fragment.getCarouselView().setAdapter(cvAdapter);
//                    fragment.getCarouselView().setRoundDotVisible(false);
//                }

            }

            @Override
            public void error(@NotNull String arg1, @NotNull Object arg2) {
                showToastMsg(arg1);
            }
        });
        shopPresenter.getApp();
//        setTitle(false, "商铺");
        initCenterShopClassfy();
    }

    private void initCenterShopClassfy() {
        List<CategoryGoodsDetailsBean> array = new ArrayList<>();
        shop_center_classfy.setLayoutManager(new LinearLayoutManager(getActivity()));
        shop_center_classfy.setNestedScrollingEnabled(true);
        centerAdapter = new ShopCenterClassfyAdapter(getActivity(), array);
        shop_center_classfy.setAdapter(centerAdapter);
        centerAdapter.setOnRvItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NotNull View view, int position) {
                startActivity(new Intent(getActivity(), GoodsShopClassificationActivity.class));
            }
        });
        rv_shop_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_shop_list.setNestedScrollingEnabled(false);        //添加Android自带的分割线
        rv_shop_list.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        shopBottomAdapter = new ShopBottomGoodsAdapter(getActivity(), array);
        rv_shop_list.setAdapter(shopBottomAdapter);
        shopBottomAdapter.setOnRvItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NotNull View view, int position) {
                startActivity(new Intent(getActivity(), ShopInnerGoodsActivity.class));
            }
        });
//        rv_shop_list.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.fl_auto://智能排序
//
//                break;
//            case R.id.fl_discount://优惠活动
//
//                break;
//            case R.id.fl_shop://商家分类
//
//                break;
        }
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        int[] location = new int[2];
        ll_classfy_bottom.getLocationOnScreen(location);
        int locationY = location[1];
        Log.e("locationY", locationY + "   " + "topHeight的值是：" + ((MainActivity) getActivity()).topHeight);

        if (locationY <= ((MainActivity) getActivity()).topHeight && (ll_classfy_top.getVisibility() == View.GONE || ll_classfy_top.getVisibility() == View.INVISIBLE)) {
            ll_classfy_top.setVisibility(View.VISIBLE);
//            ll_classfy_bottom.setVisibility(View.GONE);
        }

        if (locationY > ((MainActivity) getActivity()).topHeight && ll_classfy_top.getVisibility() == View.VISIBLE) {
            ll_classfy_top.setVisibility(View.GONE);
//            ll_classfy_bottom.setVisibility(View.VISIBLE);
        }
    }
}
